<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v6;

use app\common\model\Slide;

/**
 * 启动页
 * Class StartupPage
 * @package app\api\controller\v6
 */
class StartupPage
{
    /**
     * app启动页
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $width = input('width/d');
        $height = input('height/d');

        $scale = $height / $width;

        $data = (new Slide())->getStartPageVersion();

        $arr = [
            'name' => $data['name'],
            'description' => $data['description'],
            'target' => $data['target'],
            'link' => htmlspecialchars_decode($data['link']),
            'image' => $data['image']
        ];

        // 后端所有的尺寸
        $photoList = [];

        if (isset($data['photo']) && !empty($data['photo']))
        {
            $photos = unserialize($data['photo']);

            foreach ($photos as $k => $photo)
            {
                $temp1 = explode('|', $photo);

                $url = $temp1[0];
                $photoScale = 99;

                if (count($temp1) === 2)
                {
                    $temp2 = explode('*', $temp1[1]);

                    if (count($temp2) === 2 && $temp2[0] != 0)
                    {
                        $photoScale = $temp2[1] / $temp2[0];
                    }
                }
                // 计算屏幕尺寸差值
                $photoList[] = [
                    'url' => htmlspecialchars_decode($url),
                    'scale' => abs($photoScale - $scale),
                ];
            }
        }

        if (!empty($photoList))
        {
            // 重新排序
            $photoList = resort($photoList, 'scale', 'ASC');

            $arr['image'] = $photoList[0]['url'];
        } else
        {
            if ($scale >= 1.9)
            {
                $arr['image'] = $data['image2'];
            }
        }
        return show(config('code.success'), '加载成功', $arr);
    }
}
